<?php
/**
 * 读取配置数据
 *
 * eg: CONFIG('credits.login_add_credits.30')
 *
 * @package Helpers
 * @param	string	$key       配置文件KEY
 * @param   string  $delimiter 分隔符|默认为 .
 * @return	mixed
 */
if ( ! function_exists('CONFIG')){
	function CONFIG($key,$delimiter = '.'){
		if(!$key) return FALSE;
		$key_array = explode($delimiter, $key);
		$result = array();

		$ci = &get_instance();
		$ci->config->load($key_array[0],true);
		$result = $ci->config->item($key_array[0]);

		foreach ($key_array as $v) {
			if($v != $key_array[0]){
				if(isset($result[$v])) $result = $result[$v];
				else return false;
			}
		}

		return $result;
	}
}




/**
 * 加载模型
 * @param sting  $model_name  模型名称
 * @return Model
 */
if( ! function_exists('MODEL')){
	function MODEL($model_name){
		$model_name = strtolower($model_name);
		$ci = &get_instance();
		$ci->load->model($model_name);
		return $ci->$model_name;
	}
}

/**
 * 加载Libraries
 * @param  string $lib_name  库名称
 * @param  array  $config     初始化参数
 * @return object
 */
if( ! function_exists('LIB')){
	function LIB($lib_name,$config=NULL){
		$lib_name = strtolower($lib_name);
		$ci = &get_instance();
		$ci->load->library($lib_name, $config);
		return $ci->$lib_name;
	}
}

/**
 * 加载辅助函数
 * @param  string $helper_name 辅助函数文件别名
 * @return object
 */
if( ! function_exists('HELPER')){
	function HELPER($helper_name){
		$helper_name = strtolower($helper_name);
		$ci = &get_instance();
		$ci->load->helper($helper_name);
	}
}

/**
 * 加密
 * @param String $encrypt_string
 * @return String
 */
if( ! function_exists('encrypt')){
	function encrypt($encrypt_string) {
		return md5($encrypt_string . ENCRYPT_SECRETS);
	}
}


/**
 * 获取ip
 * @return string ip
 */
if ( ! function_exists('get_ip')){
    function get_ip()
    {
        $CI =& get_instance();
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) { 
            $ip=$_SERVER['HTTP_CLIENT_IP']; 
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { 
            $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; 
         }else { 
            $ip=$_SERVER['REMOTE_ADDR']; 
         } 
        return $ip;
    }
}

/**
 * 获取手机归属地
 * @param string  $phone  手机号码
 * @param array | bool
 */
function get_location_by_phone($phone){
  $url="http://cx.shouji.360.cn/phonearea.php?number={$phone}";
  $locations = json_decode(curl_get($url),true);
  if(empty($locations['data'])){
  	$location = '';
  	db_log('location_phone' , 'phone:'.$phone.',360-api:'.json_encode($locations));
  } else {
  	$location = $locations['data']; 	
  }
  
  if($location){	
  	$return = array('location'=>$location['province'].$location['city']);
	if($location['city']=='襄樊') $location['city']='襄阳';
    if($location['province']){
		$district = new Models\District;
		$province = $district->select('id,name')->where('name',$location['province'])->where('upid',0)->get_one();
		if($province) $return['province'] = array('id'=>$province['id'],'name'=>$province['name']);
		if($location['city']){
			$city = $district->select('id,name')->where('name',$location['city'])->where('level',2)->get_one();
			if($city) $return['city'] = array('id'=>$city['id'],'name'=>$city['name']);
		}
    }
    return $return;
  }else{
  	return false;
  }
  
}



//===================验证函数======================
/**
 * 是否是手机号码
 *@param integre  $mobile  手机号码
 *@return bool
 */
if( ! function_exists('is_mobile')){
	function is_mobile($mobile){
		if(preg_match("/^1[3456789]{1}\d{9}$/",$mobile)){  
		    return TRUE; 
		}else{  
		    return FALSE;
		}  
	}
}

/**
 *是否电子邮箱
 *@param string  $email  电子邮箱
 *@return bool
 */
if( ! function_exists('is_email')){
	function is_email($email){
		return filter_var($email,FILTER_VALIDATE_EMAIL)?TRUE:FALSE;
	}
}

/**
 *是否Url
 *@param string $url  url地址
 *@return bool
 */
if( ! function_exists('is_url')){
	function is_url($url){
		return filter_var($url,FILTER_VALIDATE_URL)?TRUE:FALSE;
	}
}

/**
 *是否IP地址
 *@param string $ip  ip地址
 *@return bool
 */
if( ! function_exists('is_ip')){
	function is_ip($ip){
		return filter_var($ip,FILTER_VALIDATE_IP)?TRUE:FALSE;
	}
}

/**
 * 是否密码
 *@param string $password 密码
 *@return bool
 */
if( ! function_exists('is_password')){
	function is_password($password){
		if(trim($password)) return TRUE;
		else return FALSE;

		if(preg_match("/^(w){4,20}$/",$psd,$password)){  
      	    return TRUE;  
  		}else{
  			return FALSE;
  		}  
	}
}

//===============验证函数END======================

/**
 *是否是AJAX请求
 *@return bool
 */
if( ! function_exists('is_ajax_request')){
	function is_ajax_request(){
		if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"){ 
		   return TRUE;
		}else{ 
		   return FALSE;
		};
	}
}

/**
 * 是否为手机访问
 * @return bool
 */
if( ! function_exists('is_mobile_request')){
	function is_mobile_request(){
		$ci = & get_instance();
		$ci->load->library('user_agent');
		return  $ci->agent->is_mobile();
	}
}

//===============CURL函数=================

/**
 * curl get请求
 * @param  string $url 请求地址
 * @return string
 */
if( ! function_exists('curl_get')){
	function curl_get($url){
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);
		$result = curl_exec($ch);
		curl_close($ch);
		return $result;
	}
}

/**
 * curl POST请求
 * @param string $url   请求地址
 * @param array  $data  请求数据
 * @return string
 */
if( ! function_exists('curl_post')){
	function curl_post($url,$data){		
		$ch = curl_init();
		$post_data = array();
		if(is_array($data)) $post_data = http_build_query($data);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_POST, true);  
		curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
		curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
		curl_setopt($ch, CURLOPT_URL, $url);
		
		$result = curl_exec($ch);
		
		curl_close($ch);
		return $result;
	}
}

/**
 * 以post方式提交xml到对应的接口url
 * 
 * @param string $xml  需要post的xml数据
 * @param string $url  url
 * @param bool $useCert 是否需要证书，默认不需要
 * @param int $second   url执行超时时间，默认30s
 * @throws WxPayException
 */
function curl_post_xml($xml, $url, $useCert = false, $second = 30){		
	$ch = curl_init();
	//设置超时
	curl_setopt($ch, CURLOPT_TIMEOUT, $second);
	curl_setopt($ch,CURLOPT_URL, $url);
	
	curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
	curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验2
	//设置header
	curl_setopt($ch, CURLOPT_HEADER, FALSE);
	//要求结果为字符串且输出到屏幕上
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);	
	//post提交方式
	curl_setopt($ch, CURLOPT_POST, TRUE);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
	//运行curl
	$data = curl_exec($ch);
	if($data){
		curl_close($ch);
		return $data;
	} else { 
		$error = curl_errno($ch);
		curl_close($ch);
		return FALSE;
	}
}

//=============== CURL END ===================

//=============== 数组函数 ===================
/**
* 将多维数组某个值转为该数组的key
*
* [['id'=>15,'name'=>'北京']] 变成 ['15'=>['id'=>15,'name'=>'北京']]
* @param array  $array  数组
* @param string $field  key名
* @return
*/
if(!function_exists('arr_key')){
	function arr_key($array,$field = 'id'){
		$new_array = array();
		foreach ($array as $key => $value) {
			$new_array[$value[$field]] = $value;
		}
		return $new_array;
	}
}

/**
* 将一维数组转化为二维数组 
* @param array  $array    数组
* @param string $id_key   id键 
* @param string $name_key name键
* @return array
*/
if(!function_exists('arr_arr')){
	function arr_arr($array,$id_key = 'id',$name_key = 'name'){
		$new_array = array();
		foreach ($array as $key => $value) {
			$new_array[$key][$id_key] = $key;
			$new_array[$key][$name_key] = $value;
		}
		return $new_array;
	}
}


/**
 * 将二维数组转化为XML
 * @param array $array 二维数组
 */
function arr_2_xml($array){
	if(!is_array($array) || count($array) <= 0){
		return FALSE;
	}
	
	$xml = "<xml>";
	foreach ($array as $key=>$val)
	{
		if (is_numeric($val)){
			$xml.="<".$key.">".$val."</".$key.">";
		}else{
			$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
		}
    }
    $xml.="</xml>";
    return $xml; 
}

/**
 * 将XML转化为数组
 * @param string  $xml  xml
 */
function xml_2_arr($xml){
	libxml_disable_entity_loader(true);
    return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);				
}

//=============== 数组函数 END  ==============

//===============EXCEL 函数 ==================

/**
* 读取Excel文件转化为数组
* @param string  $filename  文件路劲
* @return array
*/
if(!function_exists('load_excel')){
	function load_excel($filename){
		try{
			$excel = PHPExcel_IOFactory::load($filename);
		}catch(PHPExcel_Reader_Exception $e) {
			return false;
		}

		$objWorksheet = $excel->getActiveSheet();
		$highestRow = $objWorksheet->getHighestRow(); 
		$highestColumn = $objWorksheet->getHighestColumn();
		$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//总列数
		$returnArray = array('column'=>$highestColumnIndex,'row'=>$highestRow,'data'=>array());
	   
	    for ($row = 1;$row <= $highestRow;$row++){
	    	$strs=array();
	    	for ($col = 0;$col < $highestColumnIndex;$col++){
	            $strs[$col] =$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
	        }   
	        $returnArray['data'][] = $strs;
	    }
	    
	    return $returnArray;
	}
}

//===============EXCEN END ===================



//=============== 字符串函数  =================
/**
 * 截取UTF-8编码下字符串的函数
 *
 * @param   string      $str        被截取的字符串
 * @param   int         $length     截取的长度
 * @param   bool        $append     是否附加省略号
 *
 * @return  string
 */
if(!function_exists('sub_str')) {
        function sub_str($str, $length = 0, $append = true)
        {
            $str = trim($str);
            $strlength = strlen($str);
       
            if ($length == 0 || $length >= $strlength)
            {
                return $str;
            }
            elseif ($length < 0)
            {
                $length = $strlength + $length;
                if ($length < 0)
                {
                    $length = $strlength;
                }
            }
       
            if (function_exists('mb_substr'))
            {
                $newstr = mb_substr($str, 0, $length, 'utf-8');
            }
            elseif (function_exists('iconv_substr'))
            {
                $newstr = iconv_substr($str, 0, $length, 'utf-8');
            }
            else
            {
                $newstr = substr($str, 0, $length);
            }
       
            if ($append && $str != $newstr)
            {
                $newstr .= '...';
            }
       
            return $newstr;
        }
}
//============= 字符串函数END  =================
if (!function_exists('predis')) {
	function predis() {
		return new \Predis\Client([
			'scheme' => 'tcp',
            'host' => '127.0.0.1',
            'port' => 6380,
            'password' => 'local'
		]);
	}
}

/**
 * 判断用户来源
 * @return bool
 */
function is_wap(){
	$CI =& get_instance();
	$CI->load->library('user_agent');
	if($CI->agent->is_mobile()){
		return TRUE;
	}else{
		return FALSE;
	}
}

function get_order_status($status,$lang="chinese") {
	$s = CONFIG('basic.order_status');
	if(isset($s[$status])){
		return $s[$status][$lang];
	}else{
		return '';
	}
}

function get_username($first_name, $last_name) {
	$cn = preg_match("/[".chr(0xa1)."-".chr(0xff)."]/", $first_name.$last_name);
	if ($cn) {
		return $first_name.$last_name;
	} else {
		return $last_name.$first_name;
	}
}
